<template>
	<om-addpage style="padding-top: 35px;" :showChooseBtn="ismenu" :menuList='menuList' :menuName="menuName" @formSubmit="formSubmit" :busCode="busCode">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>

<script>
	import {
		getUrl,
		confirmModal,
		errorModal,
		ptFloat,
		minusF
	} from '@/static/js/common.js';
	import {
		buildFormData,
		formValidation,
		tranferToEditors,
		changeEditor,
		setSubmitSubValue,
		configSelectData,
		hasValue,
		hasEditor,
		getEditorTitle,
		changeConfigAttr,
		formShowLoading,
		getFormFields,
		formModelLoad,
		getWorkCacheKey
	} from '@/static/js/formUtil.js';
	import urlUtil from '@/static/js/urlUtil.js';
	import moment from '@/static/js/moment.js'
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';

	export default {
		data() {
			return buildFormData({
				teamLeaderCache:'wms-rkgl-finishedTreasury-teamLeader-cache',
				productionTeamCache:'wms-rkgl-finishedTreasury-productionTeam-cache',
				pieceUserCache:'wms-rkgl-finishedTreasury-pieceUser-cache',
				defaultDataCache:'wms-rkgl-finishedTreasury-defaultData-cache',
				productInstCache:'wms-rkgl-finishedTreasury-productInst-cache',
				stagnateResponsibleInstCache:'wms-rkgl-finishedTreasury-stagnateResponsibleInst-cache',
				menuList:[],
				ismenu:false,
				currencyCache:'wms-rkgl-finishedTreasury-currency-cache',
				affiliatedInstCache:'wms-rkgl-finishedTreasury-affiliatedInst-cache',
				deliveryWarehouseCache:'wms-rkgl-finishedTreasury-deliveryWarehouse-cache',
				warehousingUserCache:'wms-rkgl-finishedTreasury-warehousingUser-cache'
			})
		},
		computed: {
			...mapState(useLoginUserStore, ['userName', 'userId','salaryInstId','salaryInstName'])
		},
		provide() {
			return {
				formPage: this
			}
		},
		methods: {
			changeWarehousingUserId(id,name){
				let _that = this
				if(_that.subEditorObj['title2'] && _that.subEditorObj['title2'].workList.length>0){
					for(let dataItem of _that.subEditorObj['title2'].workList){
						_that.$set(dataItem,'warehousingUserId',id)
						_that.$set(dataItem,'warehousingUserName',name)
					}
					_that.om.toast('子表已更新')
				}
			},
			changeDeliveryWarehouse(id,name){
				let _that = this
				if(_that.subEditorObj['title2'] && _that.subEditorObj['title2'].workList.length>0){
					for(let dataItem of _that.subEditorObj['title2'].workList){
						_that.$set(dataItem,'deliveryWarehouseId',id)
						_that.$set(dataItem,'deliveryWarehouseName',name)
					}
					_that.om.toast('子表已更新')
				}
			},
			getWorkParam(){
				let _that = this
				let formdata = _that.$refs.autoform.formdata
				return {
					productInstId:formdata.productInstId,
					productInstName:formdata.productInstName,
					stagnateResponsibleInstId:formdata.stagnateResponsibleInstId,
					stagnateResponsibleInstName:formdata.stagnateResponsibleInstName,
					salaryDate:formdata.salaryDate,
					pieceComputationMethodId:formdata.pieceComputationMethodId,
					pieceComputationMethodName:formdata.pieceComputationMethodName,
					deliveryWarehouseId:formdata.deliveryWarehouseId,
					deliveryWarehouseName:formdata.deliveryWarehouseName,
					deliveryWarehouseCode:formdata.deliveryWarehouseCode,
					warehousingUserId:formdata.warehousingUserId,
					warehousingUserName:formdata.warehousingUserName,
					productTime:formdata.productTime
				}
			},
			clearTeamLeader(){
				let _that = this
				_that.$refs.autoform.clear("title1","teamLeaderId")
				_that.$refs.autoform.clear("title1","productionInstId")
				_that.$refs.autoform.changeEditor("title1","productionInstId","data",[])
			},
			onSelectProductTime(val){
				let _that = this
				let formdata = _that.$refs.autoform.formdata
				if(formdata.treasuryTime){
					let title1 = _that.$refs.autoform.getEditorTitle("title1","treasuryTime")
					let title2 = _that.$refs.autoform.getEditorTitle("title1","productTime")
					if(moment(val).isAfter(formdata.treasuryTime)){
						_that.$refs.autoform.clear("title1","productTime")
						_that.om.toast(title2+'不能晚于' + title1)
					}else{
						if(_that.subEditorObj['title2'] && _that.subEditorObj['title2'].workList.length>0){
							for(let dataItem of _that.subEditorObj['title2'].workList){
								_that.$set(dataItem,'productTime',val)
							}
							_that.om.toast('子表已更新')
						}
					}
				}
			},
			onSelectPieceComputationMethod(item){
				let _that = this
				if(_that.subEditorObj['title2'] && _that.subEditorObj['title2'].workList.length>0){
					for(let dataItem of _that.subEditorObj['title2'].workList){
						_that.$set(dataItem,'pieceComputationMethod',item.id)
						_that.$set(dataItem,'pieceComputationMethodName',item.text)
					}
					_that.om.toast('子表已更新')
				}
			},
			changeProductionTeamId(id,text){
				let _that = this
				if(_that.subEditorObj['title2'] && _that.subEditorObj['title2'].workList.length>0){
					for(let item of _that.subEditorObj['title2'].workList){
						_that.$set(item,'productionTeamId',id)
						_that.$set(item,'productionTeamName',text)
					}
					_that.om.toast('子表已更新')
				}
			},
			changeStagnateResponsibleInst(id,text){
				let _that = this
				if(_that.subEditorObj['title2'] && _that.subEditorObj['title2'].workList.length>0){
					for(let item of _that.subEditorObj['title2'].workList){
						_that.$set(item,'stagnateResponsibleInstId',id)
						_that.$set(item,'stagnateResponsibleInstName',text)
					}
					_that.om.toast('子表已更新')
				}
			},
			changeProductInstId(id,text){
				let _that = this
				if(_that.subEditorObj['title2'] && _that.subEditorObj['title2'].workList.length>0){
					for(let item of _that.subEditorObj['title2'].workList){
						_that.$set(item,'productInstId',id)
						_that.$set(item,'productInstName',text)
					}
					_that.om.toast('子表已更新')
				}
			},
			getUserPosAddSalary(userId){
				let _that = this
				_that.om.request(
					"temployee/getUserPosAddSalary",
					{
						userId: userId
					}
				).then(res=>{
					_that.$refs.autoform.formdata.productionInstId = res.value.salaryPosInstId
					_that.$refs.autoform.formdata.productionInstName = res.value.salaryPosInstName
					_that.findInstByUserIdOrPostId(userId)
				})
			},
			findInstByUserIdOrPostId(userId){
				let _that = this
				_that.om.request(
					'orgInstPosUserOfficial/findInstByUserIdOrPostId',
					{
						userId:userId
					}
				).then(res=>{
					_that.$refs.autoform.changeEditor("title1","productionInstId","data",configSelectData(res,'id','instName'))
					_that.$refs.autoform.initSelectIndex("title1","productionInstId")
				})
			},
			initLoad(options) {
				let _that = this;
				var fileId = options.fileId
				let ajaxArr = [
					{
						url:'currencyDict/getLocalCurrency'
					},
					{
						url:'dictSource/loadCombo',
						param:{
							sourceId:'289',
							categoryId:'8646'
						}
					},
					{
						url:'common/getMenu',
						param:{
							formCode:options.code
						},
					}
				]
				if(fileId){
					ajaxArr.push(
						{
							url:'finishedTreasury/getValue',
							param:{
								fileId:fileId
							}
						}
					)
				}
				formModelLoad(ajaxArr, function(res, mainData) {
					_that.menuList =  res[2].value
					changeEditor("title1","productTime",'noInitDate',true,mainData)
					changeEditor("title1","currencyId",{
						defaultValue:res[0].value.id,
						defaultName:res[0].value.currencyName
					},null,mainData)
					changeEditor("title1","affiliatedInstId",{
						"link":'../../public/search/search',
						"linkParam":{
							other:JSON.stringify(),
							url:'tinstitution/getComboTree',
							namefield:'text',
							initload:true,
							cachename:_that.affiliatedInstCache
						}
					},null,mainData)
					changeEditor("title1","currencyId",{
						link:'../../public/pageSearch/pageSearch',
						"linkParam":{
							other:JSON.stringify({}),
							url:'currencyDict/getCurrency',
							namefield:'currencyName',
							initload:true,
							cachename:_that.currencyCache
						}
					},null,mainData)
					changeEditor("title1","deliveryWarehouseId",{
						link:'../../public/pageSearch/pageSearch',
						"linkParam":{
							other:JSON.stringify({
								firstId:''
							}),
							url:'warehouseArchives/getWarehouseArchivesPager',
							namefield:'typeName',
							initload:true,
							cachename:_that.deliveryWarehouseCache
						}
					},null,mainData)
					if(_that.subEditorObj["title2"]){
						let attr = {
							getWorkParam:'getWorkParam'
						}
						let configData = _that.subConfigData["title2"]
						if(hasEditor("title2","newProductName",configData)){
							let title = getEditorTitle("title2","newProductName",configData)
							attr.titleTemplate = title+':<%= newProductName %>'
						} 
						if(hasEditor("title2","newProductId",configData)){
							let title = getEditorTitle("title2","newProductId",configData)
							attr.subtitle1Template = title+':<%= newProductCode %>'
						}
						changeEditor("title2","dataStr",attr,mainData)
					}
					
					changeEditor("title1","pieceComputationMethodId","data",configSelectData(res[1],'id','text'),mainData)
					changeEditor("topinfo","zinstId",{
						defaultValue:_that.salaryInstId,
						defaultName:_that.salaryInstName
					},null,mainData)
					changeEditor("title1","teamLeaderId",{
						link:'../../public/searchUser/searchUser',
						"linkParam":{
							cachename: _that.teamLeaderCache,
							isSingle:true,
							isUserPos:true,
							isNew:true
						}
					},null,mainData)
					changeEditor("title1","pieceUserIdStr",{
						link:'../../public/searchUser/searchUser',
						"linkParam":{
							cachename: _that.pieceUserCache,
							defaultDataCache:_that.defaultDataCache,
							isNew:true
						}
					},null,mainData)
					changeEditor("title1","productionTeamId",{
						link:'../../public/search/search',
						"linkParam":{
							other:JSON.stringify({
								sourceId:'289',
								categoryId:'8155'
							}),
							url:'dictSource/loadCombo',
							initload:true,
							namefield:'text',
							cachename: _that.productionTeamCache,
						}
					},null,mainData)
					
					changeEditor("title1","productInstId",{
						link:'../../public/search/search',
						"linkParam":{
							other:JSON.stringify({
								
							}),
							url:'tinstitution/getComboTree',
							initload:true,
							namefield:'text',
							cachename: _that.productInstCache,
						}
					},null,mainData)
					
					changeEditor("title1","stagnateResponsibleInstId",{
						link:'../../public/search/search',
						"linkParam":{
							other:JSON.stringify({
								
							}),
							url:'tinstitution/getComboTree',
							initload:true,
							namefield:'text',
							cachename: _that.stagnateResponsibleInstCache,
						}
					},null,mainData)
					changeEditor("title1","sourceFormCode",'disabled',true,mainData)
					
					changeEditor("title1","warehousingUserId",{
						"link":'../../public/searchUser/searchUser',
						"linkParam":{
							other:JSON.stringify({
							}),
							isSingle:true,
							isUserPos:true,
							isNew:true,
							cachename:_that.warehousingUserCache
						}
					},null,mainData)
					
					// let tempFileList = []
					// let fileUrlList = []
					// changeEditor('bottominfo','bottomFileUpload','fileUploadKey',"43",mainData)
					// changeEditor("bottominfo","bottomFileUpload","tempFileList", tempFileList,mainData)
					// changeEditor("bottominfo","bottomFileUpload","fileUrlList", fileUrlList,mainData)
					
					if(fileId){
						let fieldArr = getFormFields(mainData)
						fieldArr.push('id')
						for(let index in res[3].value){
							if(fieldArr.includes(index)){
								_that.$refs.autoform.$set(_that.$refs.autoform.formdata,index,res[3].value[index])
								_that.$set(_that.formdata,index,res[3].value[index])
							}
						}
						
						if(_that.subEditorObj['title2']){
							let dataList = res[3].value.dataList
							_that.subEditorObj["title2"].workList = dataList
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "dataStr", JSON.stringify(dataList))
							_that.$set(_that.formdata, "dataStr", JSON.stringify(dataList))
						}
						
						// if(_that.formdata.bottomFileList){
						// 	let tempFileList = []
						// 	let fileUrlList = _that.formdata.bottomFileList.map(t=>{
						// 		tempFileList.push(t.fileSaveName)
						// 		return t.fileSaveName
						// 	})
						// 	changeEditor("bottominfo","bottomFileUpload","tempFileList", tempFileList,mainData)
						// 	changeEditor("bottominfo","bottomFileUpload","fileUrlList", fileUrlList,mainData)
						// }
						
					}
					
					_that.$nextTick(function(){
						_that.$refs.autoform.initSelectIndex("title1","pieceComputationMethodId")
					})
				}, options)
			},
			formSubmit() {
			  let _that = this
			  let dataList = []
			  _that.formdata.updateBottomFileFlag= false
			  delete _that.formdata.bottomFileUpload
			  delete _that.formdata.bottomFileList
			  
			  if(_that.formdata.dataStr){
				dataList = JSON.parse(_that.formdata.dataStr)
				for(let item of dataList){
					if(!item.fileList){
						delete item.fileList
					}
					if(!item.workList){
						item.workList = []
					}
				}
			  _that.formdata.dataStr = JSON.stringify(dataList)
			  }
			  if(!_that.edit){
				  _that.om.formSave('finishedTreasury/doAdd',_that.formdata,_that)
			  }else{
				  _that.om.formSave('finishedTreasury/doUpdate',_that.formdata,_that)
			  }
			}
		},
		onUnload(){
		let _that = this;
		uni.removeStorage({
			key:_that.defaultDataCache
		})
		//#ifdef APP-PLUS
			if (_that.$refs.autoform) {
				for (var fieldId in _that.subEditorObj) {
					uni.removeStorage({
						key: getWorkCacheKey(fieldId)
					});
				}
			}
		//#endif
		},
		onLoad(options) {
			this.initValue.userinfoId = this.userId
			this.initLoad(options)
		},
		onShow() {
			let _that = this;
			if (_that.$refs.autoform) {
				for (var fieldId in _that.subEditorObj) {
					var editor = _that.subEditorObj[fieldId];
					uni.getStorage({
						key: getWorkCacheKey(fieldId),
						success: function(res) {
							editor.workList = res.data;
							let formdata = _that.$refs.autoform.formdata
							for(let item of editor.workList){
								if(item.productInstId){
									if(formdata.productInstId && item.productInstId != formdata.productInstId){
										_that.$refs.autoform.clear("title1","productInstId")
									}
								}
								if(item.stagnateResponsibleInstId){
									if(formdata.stagnateResponsibleInstId && item.stagnateResponsibleInstId != formdata.stagnateResponsibleInstId){
										_that.$refs.autoform.clear("title1","stagnateResponsibleInstId")
									}
								}
								if(item.salaryDate){
									if(formdata.salaryDate && item.salaryDate != formdata.salaryDate){
										_that.$refs.autoform.clear("title1","salaryDate")
									}
								}
								if(item.deliveryWarehouseId){
									if(formdata.deliveryWarehouseId && item.deliveryWarehouseId != formdata.deliveryWarehouseId){
										_that.$refs.autoform.clear("title1","deliveryWarehouseId")
										_that.$refs.autoform.clear("title1","deliveryWarehouseCode")
									}
								}
								if(item.warehousingUserId){
									if(formdata.warehousingUserId && item.warehousingUserId != formdata.warehousingUserId){
										_that.$refs.autoform.clear("title1","warehousingUserId")
									}
								}
								if(item.productTime){
									if(formdata.productTime && item.productTime != formdata.productTime){
										_that.$refs.autoform.clear("title1","productTime")
									}
								}
							}
							uni.removeStorage({
								key: getWorkCacheKey(fieldId)
							});
						}
					});
				};
				uni.getStorage({
					key:_that.affiliatedInstCache,
					success:(res)=>{
						let d = res.data
						let formdata = _that.$refs.autoform.formdata
						formdata.affiliatedInstId = d.id
						formdata.affiliatedInstName = d.text
						uni.removeStorage({
							key:_that.affiliatedInstCache
						})
					}
				})
				uni.getStorage({
					key:_that.teamLeaderCache,
					success:(res)=>{
						if(res.data){
							let d = res.data[0]
							let formdata = _that.$refs.autoform.formdata
							formdata.teamLeaderId = d.id
							formdata.teamLeaderName = d.username
							_that.getUserPosAddSalary(d.id)
							uni.removeStorage({
								key:_that.teamLeaderCache
							})
						}
					}
				});
				uni.getStorage({
					key:_that.productionTeamCache,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.productionTeamId = d.id
							formdata.productionTeamName = d.text
							_that.changeProductionTeamId(d.id,d.text)
							uni.removeStorage({
								key:_that.productionTeamCache
							})
						}
					}
				})
				uni.getStorage({
					key:_that.pieceUserCache,
					success:(res)=>{
						if (res.data) {
							let d = res.data;
							uni.setStorage({
								key:_that.defaultDataCache,
								data:d
							})
							var formdata = _that.$refs.autoform.formdata;
							let idList = []
							let nameList = []
							let pieceUserIdStr = ''
							if(formdata.pieceUserIdStr){
								pieceUserIdStr = formdata.pieceUserIdStr.split(',')
							}
							for(let index in d){
								idList.push(d[index].id)
								nameList.push(d[index].username)
							}
							let idStr = idList.map(e =>e).join(",")
							let pieceUserNameStr = nameList.map(e =>e).join(",");
							formdata.pieceUserIdStr = idStr
							formdata.pieceUserNameStr = pieceUserNameStr
							uni.removeStorage({
								key: _that.pieceUserCache
							});
						}
					}
				})
				uni.getStorage({
					key:_that.deliveryWarehouseCache,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.deliveryWarehouseId = d.id
							formdata.deliveryWarehouseName = d.typeName
							formdata.deliveryWarehouseCode = d.code
							_that.changeDeliveryWarehouse(d.id,d.typeName)
							uni.removeStorage({
								key:_that.deliveryWarehouseCache
							})
						}
					}
				})
				uni.getStorage({
					key:_that.warehousingUserCache,
					success:(res)=>{
						if(res.data){
							let d = res.data[0]
							let formdata = _that.$refs.autoform.formdata
							formdata.warehousingUserId = d.id
							formdata.warehousingUserName = d.username
							_that.changeWarehousingUserId(d.id,d.username)
							uni.removeStorage({
								key:_that.warehousingUserCache
							})
						}
					}
				})
				uni.getStorage({
					key:_that.productInstCache,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.productInstId = d.id
							formdata.productInstName = d.text
							_that.changeProductInstId(d.id,d.text)
							uni.removeStorage({
								key:_that.productInstCache
							})
						}
					}
				})
				uni.getStorage({
					key:_that.stagnateResponsibleInstCache,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.stagnateResponsibleInstId = d.id
							formdata.stagnateResponsibleInstName = d.text
							_that.changeStagnateResponsibleInst(d.id,d.text)
							uni.removeStorage({
								key:_that.stagnateResponsibleInstCache
							})
						}
					}
				})
				uni.getStorage({
					key:_that.currencyCache,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.currencyId = d.id
							formdata.currencyName = d.currencyName
							uni.removeStorage({
								key:_that.currencyCache
							})
						}
					}
				})
				try {
					const value = uni.getStorageSync('chooseData');
					if (value) {
						let arr= []
						let objList = []
						let formdata = _that.$refs.autoform.formdata
						formdata.pieceUserIdStr = value[0].pieceUserIdStr
						formdata.pieceUserNameStr = value[0].pieceUserNameStr
						formdata.teamLeaderId = value[0].teamLeaderId
						formdata.teamLeaderName = value[0].teamLeaderName
						formdata.productionInstId = value[0].productionInstId
						formdata.productionInstName = value[0].productionInstName
						_that.findInstByUserIdOrPostId(value[0].teamLeaderId)
						formdata.productionTeamId = value[0].productionTeamId
						formdata.productionTeamName = value[0].productionTeamName
						formdata.productDate = value[0].firstBatchCompletionDate
						formdata.productInstId = value[0].productInstId
						formdata.productInstName = value[0].productInstName
						formdata.stagnateResponsibleInstId = value[0].stagnateResponsibleInstId
						formdata.stagnateResponsibleInstName = value[0].stagnateResponsibleInstName
						formdata.affiliatedInstId = value[0].affiliatedInstId
						formdata.affiliatedInstName = value[0].affiliatedInstName
						formdata.currencyId = value[0].currencyId
						formdata.currencyName = value[0].currencyName
						formdata.pieceComputationMethodId = value[0].pieceComputationMethodId
						formdata.pieceComputationMethodName = value[0].pieceComputationMethodName
						_that.$refs.autoform.initSelectIndex("title1","pieceComputationMethodId")
						formdata.salaryDate = value[0].salaryDate
						formdata.remark = value[0].remark
						formdata.sourceFormId = value[0].busId
						formdata.sourceForm = value[0].busName
						formdata.sourceFormCode = value.map(e=>e.code).join(',')
						let idList = value[0].pieceUserIdStr.split(",")
						let nameList = value[0].pieceUserNameStr.split(",")
						for(let index in idList){
							let obj = {
								id:idList[index],
								username:nameList[index]
							}
							objList.push(obj)
						}
						uni.setStorage({
							key:_that.defaultDataCache,
							data:objList
						})
						for(let item of value){
							for(let subItem of item.subData){
								if(subItem.checked){
									subItem.sourceFormId = item.busId
									subItem.sourceForm = item.busName
									subItem.sourceFormCode= item.code
									subItem.newBatchNumber = subItem.batchNumber
									if(subItem.productionQuantity){
										subItem.deliveryQuantity = subItem.productionQuantity
									}
									delete subItem.batchNumber
									arr.push(subItem)
								}
							}
						}
						if(_that.subEditorObj["title2"]){
							_that.subEditorObj["title2"].workList = arr
						}
						uni.removeStorageSync('chooseData')
					}
				} catch (e) {
					// error
				}
				
			}
		}
	}
</script>

<style>
</style>
       